package sapling.utils;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import sapling.model.Log;
import sapling.model.Tree;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class ExcelUtil {

    @Value("${web.poi-path}")
    private static String imgdir="file";
    
    public static HSSFWorkbook getHSSFWorkbook(String sheetName,String []title,String [][]values, HSSFWorkbook wb){
         // 第一步，创建一个webbook，对应一个Excel文件  
        if(wb == null){
            wb = new HSSFWorkbook();
        }
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet  
        HSSFSheet sheet = wb.createSheet(sheetName);  
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short  
        HSSFRow row = sheet.createRow(0);  
        // 第四步，创建单元格，并设置值表头 设置表头居中  
        HSSFCellStyle style = wb.createCellStyle();  
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式  
        
        HSSFCell cell = null;  
        //创建标题
        for(int i=0;i<title.length;i++){
            cell = row.createCell(i);  
            cell.setCellValue(title[i]);  
            cell.setCellStyle(style);  
        }
        //创建内容
        for(int i=0;i<values.length;i++){
            row = sheet.createRow(i + 1); 
            for(int j=0;j<values[i].length;j++){
                 row.createCell(j).setCellValue(values[i][j]);
            }
        }
        
       return wb;
    }


    public static String exportOPut(List<Tree> trees,String place,String time) {
        File dir=new File(imgdir);
        String fileName =System.currentTimeMillis() + ".xls"; //文件名
        String sheetName = "日志";//sheet名

        String[] title = new String[]{"苗木数量", "树种", "胸径", "高度", place, time};//标题
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String[][] values = new String[trees.size()][];
        for (int i = 0; i < trees.size(); i++) {
            values[i] = new String[title.length];
            //将对象内容转换成string
            Tree obj = trees.get(i);
            values[i][0] = obj.getNumber() + "";
            values[i][1] = obj.getTreeSpecies();
            values[i][2] = obj.getChestBreadth()+"";
            values[i][3] = obj.getHeight()+"";
            if ("产地".equals(place)) {
                values[i][4] = obj.getLocation();
                values[i][5] = sdf.format(obj.getPutNurseryTime());
            }else  if ("去向".equals(place)) {
                values[i][4] = obj.getDirection();
                values[i][5] = sdf.format(obj.getOutWarehouseTime());
            }

        }

        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, values, null);
        String startTime="";
        //将文件存到指定位置
        try {
            SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmss");
            startTime = (sd.format(new Date()))+".xls";
            FileOutputStream fout = new FileOutputStream(new File(dir.getPath(), startTime));
            wb.write(fout);
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return startTime;
    }

    public static String exportLog(List<Log> logList) {
        File dir=new File(imgdir);
        String fileName =System.currentTimeMillis() + ".xls"; //文件名
        String sheetName = "日志";//sheet名

        String[] title = new String[]{"用户名", "动作", "IP", "时间"};//标题
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String[][] values = new String[logList.size()][];
        for (int i = 0; i < logList.size(); i++) {
            values[i] = new String[title.length];
            //将对象内容转换成string
            Log log=logList.get(i);
            values[i][0] = log.getUsername();
            values[i][1] =log.getOperation();
            values[i][2] = log.getIP();
            values[i][3] = log.getOperationtime()+"";

        }

        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, values, null);
        String startTime="";
        //将文件存到指定位置
        try {
            SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmss");
            startTime = (sd.format(new Date()))+".xls";
            FileOutputStream fout = new FileOutputStream(new File(dir.getPath(), startTime));
            wb.write(fout);
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return startTime;
    }

    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
}